import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
import { Table, Form, Checkbox, Button, Icon } from 'antd';
import moment from 'moment';
import { routerRedux } from 'dva/router';
import styles from './AppointedDay.less';
import { connect } from 'dva';
const format = 'YYYY/MM/DD';
let actTimes = '';
let startTime, endTime, actId, returnData;
export default Form.create()(
	//actTimes: '9:00-10:00,14:00-15:00',
	//startTime: '2018/11/9',
	//endTime: '2018/11/20',
	/**
	 * @param {num} number -1代表上周, 0代表本周, 1代表下周
	 */
	// 计算当前周的日期
	// 获取选择的数据
	// 生成checkbox
	// 渲染column的checkbox
	//const { startTime, endTime } = this.props;
	// 当前激活的时间
	// 保存选中的时间
	// 今天的日期
	// 返回来的时间段
	// 激活的日期(默认是今天)
	// 计算date是这周第几天
	// 是否显示边框
	// 展开所有行
	// 不进行分页
	@connect(({ activity }) => ({
		activity,
	}))
	class extends Component {
		static defaultProps = {};
		calcArr = [1, 2, 3, 4, 5, 6, 7];
		currentWeek = [];
		savedCheckObj = {};
		constructor(props) {
			super(props);
			const date = moment().format(format);
			this.state = {
				date,
				activeDate: date,
			};
			this.calcWeekDate(this.state.date);
		}
		componentWillMount() {
			let preReturnData = window.sessionStorage.getItem('returnData');
			if (preReturnData == undefined || preReturnData == null) {
				this.props.dispatch(routerRedux.push({ pathname: '/activity/activity' }));
			} else {
				const obj = JSON.parse(preReturnData);
				this.state.record = obj;
				const { timeTables } = obj;
				timeTables.forEach(time => {
					if (time.appointDate) {
						const key = `${time.startTime}-${time.endTime}_${moment(time.appointDate).format(format)}`;
						this.savedCheckObj[key] = true;
					}
				});
			}
		}
		componentWillUnmount() {
			window.sessionStorage.removeItem('returnData');
		}
		changeActiveWeek = activeDate => {
			this.calcWeekDate(activeDate);
			this.setState({
				activeDate,
			});
		};
		clickWeek = num => {
			const { activeDate, date } = this.state;
			let nextDate;
			if (num === 0) {
				nextDate = date;
			} else {
				nextDate = moment(activeDate)
					.add(num * 7, 'days')
					.format(format);
			}
			this.getValues();
			this.changeActiveWeek(nextDate);
		};
		calcWeekDate = date => {
			const weekOfDay = moment(date).format('E');
			this.currentWeek = this.calcArr.map(num =>
				moment(date)
					.subtract(weekOfDay - num, 'days')
					.format(format)
			);
		};
		getValues = () => {
			const { form } = this.props;
			const values = form.getFieldsValue();
			this.savedCheckObj = Object.assign(this.savedCheckObj, values);
		};
		formCom = (name, config) => {
			const { getFieldDecorator } = this.props.form;
			return getFieldDecorator(name, {
				valuePropName: 'checked',
				initialValue: config.initVal,
			})(<Checkbox disabled={config.disabled} key={name} />);
		};
		renderColumn = d => {
			const { date } = this.state;
			const { endTime, startTime } = this.state.record;
			const { savedCheckObj } = this;
			const st = moment(startTime).format(format);
			const et = moment(endTime).format(format);
			return (text, record) => {
				const { key } = record;
				return this.formCom(`${key}_${d}`, {
					disabled: moment(d).isBefore(date) || moment(d).isAfter(et) || moment(d).isBefore(st),
					initVal: savedCheckObj[`${key}_${d}`],
				});
			};
		};
		returnValues = () => {
			this.getValues();
			const { savedCheckObj } = this;
			const {
				record: { actId },
			} = this.state;
			const keys = Object.keys(savedCheckObj);
			const arr = keys.filter(key => savedCheckObj[key]).map(date => date.split('_'));
			const finalArr = [];
			arr.forEach(([key, val]) => {
				const t = key.split('-');
				finalArr.push({
					appointDate: moment(val).format('YYYY-MM-DD'),
					startTime: t[0],
					endTime: t[1],
				});
			});
			let params = {
				actId: actId,
				appointDates: finalArr,
			};
			this.props.dispatch({
				type: 'activity/appointDay',
				payload: params,
				callback: () => this.GoBack(),
			});
			console.log('finalArr', finalArr);
		};
		GoBack = () => {
			const { dispatch } = this.props;
			dispatch(routerRedux.push({ pathname: '/activity/activity/' }));
		};
		render() {
			const {
				activeDate,
				record: { startTime, endTime, timeTables },
			} = this.state;
			const { currentWeek } = this;
			const actTimes = null;
			const columns = [
				{
					title: '预约时间',
					dataIndex: 'reservation',
					key: 'reservation',
					align: 'center',
					render: (text, record) => {
						return <span>{record.name}</span>;
					},
				},
				{
					title: `${currentWeek[0]}星期一`,
					dataIndex: 'monday',
					key: 'monday',
					align: 'center',
					render: this.renderColumn(currentWeek[0]),
				},
				{
					title: `${currentWeek[1]}星期二`,
					dataIndex: 'tuesday',
					key: 'tuesday',
					align: 'center',
					render: this.renderColumn(currentWeek[1]),
				},
				{
					title: `${currentWeek[2]}星期三`,
					dataIndex: 'wednesday',
					key: 'wednesday',
					align: 'center',
					render: this.renderColumn(currentWeek[2]),
				},
				{
					title: `${currentWeek[3]}星期四`,
					dataIndex: 'thursday',
					key: 'thursday',
					align: 'center',
					render: this.renderColumn(currentWeek[3]),
				},
				{
					title: `${currentWeek[4]}星期五`,
					dataIndex: 'friday',
					key: 'friday',
					align: 'center',
					render: this.renderColumn(currentWeek[4]),
				},
				{
					title: `${currentWeek[5]}星期六`,
					dataIndex: 'saturday',
					key: 'saturday',
					align: 'center',
					render: this.renderColumn(currentWeek[5]),
				},
				{
					title: `${currentWeek[6]}星期天`,
					dataIndex: 'sunday',
					key: 'sunday',
					align: 'center',
					render: this.renderColumn(currentWeek[6]),
				},
			];
			const temp = [];
			timeTables.forEach(item => {
				const key = `${item.startTime}-${item.endTime}`;
				if (!temp.includes(key)) {
					temp.push(key);
				}
			});
			const data = temp.map(item => ({
				key: item,
				name: item,
			}));
			const config = {
				bordered: true,
				defaultExpandAllRows: true,
				pagination: false,
			};
			const st = moment(startTime).format(format);
			const et = moment(endTime).format(format);
			const startDis = currentWeek.includes(st) || moment(activeDate).isBefore(st);
			const endDis = currentWeek.includes(et) || moment(activeDate).isAfter(et);
			return (
				<Form className={styles.con}>
					<div>
						<div className={styles.title}>选择指定日期</div>
						<div className={styles.btns}>
							<Button
								type="primary"
								disabled={startDis}
								onClick={() => this.clickWeek(-1)}
								className={styles.btn}
							>
								上周<Icon type="left" />
							</Button>
							<Button type="primary" onClick={() => this.clickWeek(0)} className={styles.btn}>
								本周
							</Button>
							<Button
								type="primary"
								disabled={endDis}
								onClick={() => this.clickWeek(1)}
								className={styles.btn}
							>
								<Icon type="right" />下周
							</Button>
						</div>
						<Table {...config} dataSource={data} columns={columns} />
						<div className={styles.tips}>
							<Checkbox checked style={{ marginRight: '5px' }}>
								活动
							</Checkbox>
							<Checkbox checked={false} style={{ marginRight: '5px' }}>
								不活动
							</Checkbox>
							<Checkbox disabled>不可选择</Checkbox>
						</div>
					</div>
					<div className={styles['handle-btns']}>
						<Button className={styles.reback} onClick={this.GoBack}>
							返回
						</Button>
						<Button type="primary" onClick={this.returnValues}>
							保存
						</Button>
					</div>
				</Form>
			);
		}
	}
);
